<?php

function aia_contacts_field_info() {
  return array(
    'aia_contacts' => array(
      'label' => t('Contacts'),
      'description' => t('Contacts'),
      'default_widget' => 'aia_contacts_widget',
      'default_formatter' => 'aia_contacts_formatter',
      'settings' => array(
        'display_field' => 0,
        'display_default' => 0,
        'allowed_values' => array(
          array(
            'vocabulary' => CONTACTS_TYPE_VOCABULARY,
            'parent' => '0',
          ),
        ),
      ),
    ),
  );
}

/**
 * Implements hook_field_widget_info().
 */
function aia_contacts_field_widget_info() {
  return array(
    'aia_contacts_widget' => array(
      'label' => t('Contacts widget'),
      'field types' => array('aia_contacts'),
      'settings' => array(
        'display_field' => 0,
        'display_default' => 0,
      ),
      'behaviors' => array(
        'multiple values' => FIELD_BEHAVIOR_CUSTOM,
        'default value' => FIELD_BEHAVIOR_NONE,
      ),
    ),
  );
}

/**
 * Implements hook_field_validate().
 */
function aia_contacts_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
// Build an array of existing term IDs so they can be loaded with
// taxonomy_term_load_multiple();
//  foreach ($items as $delta => $item) {
//    if (!empty($item['tid']) && $item['tid'] != 'autocreate') {
//      $tids[] = $item['tid'];
//    }
//  }
//  if (!empty($tids)) {
//    $terms = taxonomy_term_load_multiple($tids);
//
//// Check each existing item to ensure it can be found in the
//// allowed values for this field.
//    foreach ($items as $delta => $item) {
//      $validate = TRUE;
//      if (!empty($item['tid']) && $item['tid'] != 'autocreate') {
//        $validate = FALSE;
//        foreach ($field['settings']['allowed_values'] as $settings) {
//// If no parent is specified, check if the term is in the vocabulary.
//          if (isset($settings['vocabulary']) && empty($settings['parent'])) {
//            if ($settings['vocabulary'] == $terms[$item['tid']]->vocabulary_machine_name) {
//              $validate = TRUE;
//              break;
//            }
//          }
//// If a parent is specified, then to validate it must appear in the
//// array returned by taxonomy_get_parents_all().
//          elseif (!empty($settings['parent'])) {
//            $ancestors = taxonomy_get_parents_all($item['tid']);
//            foreach ($ancestors as $ancestor) {
//              if ($ancestor->tid == $settings['parent']) {
//                $validate = TRUE;
//                break 2;
//              }
//            }
//          }
//        }
//      }
//      if (!$validate) {
//        $errors[$field['field_name']][$langcode][$delta][] = array(
//          'error' => 'taxonomy_term_reference_illegal_value',
//          'message' => t('%name: illegal value.', array('%name' => $instance['label'])),
//        );
//      }
//    }
//  }
}

/**
 * Implements hook_field_is_empty().
 */
function aia_contacts_field_is_empty($item, $field) {
//  if (!is_array($item) || (empty($item['tid']) && (string) $item['tid'] !== '0')) {
//    return TRUE;
//  }
  return FALSE;
}

/**
 * Implements hook_field_formatter_info().
 */
function aia_contacts_field_formatter_info() {
  return array(
    'aia_contacts_formatter' => array(
      'label' => t('Link'),
      'field types' => array('aia_contacts'),
    ),
  );
}

/**
 * Implements hook_field_formatter_view().
 */
function aia_contacts_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    case 'aia_contacts_formatter':
      foreach ($items as $delta => $item) {
        $element[$delta] = array(
          '#markup' => check_plain($item),
        );
      }
      break;
  }

  return $element;
}

/**
 * Implements @see hook_field_widget_form().
 */
function aia_contacts_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $widget = array();
  $options = taxonomy_allowed_values($field);
  $default_type = key($options);

  $field_state = field_form_get_state($element['#field_parents'], $field['field_name'], $langcode, $form_state);
  if (isset($field_state['items'])) {
    $items = $field_state['items'];
  }

  switch ($instance['widget']['type']) {
    case 'aia_contacts_widget':

      if ($field['cardinality'] == 1) {
        $widget = $element;
        $widget += array(
          'type' => array(
            '#type' => 'select',
            '#options' => $options,
          ),
          'value' => array(
            '#type' => 'textfield',
          ),
          '#process' => array_merge(array(), array('aia_contacts_field_widget_process')),
        );
        $widget['#delta'] = $delta;
        $widget['type']['#default_value'] = !empty($items) ? $items[0]['type'] : $default_type;
        $widget['value']['#default_value'] = !empty($items) ? $items[0]['value'] : '';
      }
      else {
      kpr($form_state);
        if(sizeof($items) == 0) {
          $widget['items'][$delta] = $element;
          $widget['items'][$delta] += array(
            'type' => array(
              '#type' => 'select',
              '#options' => $options,
            ),
            'value' => array(
              '#type' => 'textfield',
            ),
            '#process' => array_merge(array(), array('aia_contacts_field_widget_process')),
          );
             $widget['items'][$delta]['#delta'] = $delta;
          $widget['items'][$delta]['#weight'] = $delta;
          $widget['items'][$delta]['type']['#default_value'] = !empty($item) ? $item['type'] : $default_type;
          $widget['items'][$delta]['value']['#default_value'] = !empty($item) ? $item['value'] : '';
          $delta++;
        }
        else {
          foreach ($items as $item) {
            $widget['items'][$delta] = $element;
            $widget['items'][$delta] += array(
              'type' => array(
                '#type' => 'select',
                '#options' => $options,
              ),
              'value' => array(
                '#type' => 'textfield',
              ),
              '#process' => array_merge(array(), array('aia_contacts_field_widget_process')),
            );
            $widget['items'][$delta]['#delta'] = $delta;
            $widget['items'][$delta]['#weight'] = $delta;
            $widget['items'][$delta]['type']['#default_value'] = !empty($item) ? $item['type'] : $default_type;
            $widget['items'][$delta]['value']['#default_value'] = !empty($item) ? $item['value'] : '';
            $delta++;
          }
        }

        if (($field['cardinality'] == FIELD_CARDINALITY_UNLIMITED || $delta < $field['cardinality']) && empty($form_state['programmed'])) {
          $widget[$delta] = $element;
          $widget[$delta]['#delta'] = $delta;
          $widget[$delta]['#weight'] = $delta;
          $widget[$delta]['actions'] = array(
            '#type' => 'submit',
            '#value' => t('Add'),
            '#submit' => array('aia_contact_ajax_submit'),
            '#limit_validation_errors' => array(),
            '#ajax' => array(
              'callback' => 'aia_contact_ajax_add',
              'wrapper' => 'edit-field-contacts-und-table'
            ),
          );
        }

        $widget['items']['#aia_contact_delta'] = $delta;
        $widget['items']['#theme'] = 'aia_contacts_widget_multiple';
        $widget['#theme_wrappers'] = array('fieldset');
        $widget['#title'] = $element['#title'];
        $widget['#description'] = $element['#description'];
        $widget['items']['#field_name'] = $element['#field_name'];
        $widget['items']['#language'] = $element['#language'];
        $widget['items']['#process'] = array('aia_contacts_field_widget_process_multiple');
      }

      break;
  }

  return $widget;
}

function aia_contact_ajax_submit($form, &$form_state) {
  // During the form rebuild, file_field_widget_form() will create field item
  // widget elements using re-indexed deltas, so clear out $form_state['input']
  // to avoid a mismatch between old and new deltas. The rebuilt elements will
  // have #default_value set appropriately for the current state of the field,
  // so nothing is lost in doing this.
  $parents = array_slice($form_state['triggering_element']['#parents'], 0, -2);
  drupal_array_set_nested_value($form_state['input'], $parents, NULL);

  $button = $form_state['triggering_element'];

  // Go one level up in the form, to the widgets container.
  $element = drupal_array_get_nested_value($form, array_slice($button['#array_parents'], 0, -1));
  $field_name = $element['#field_name'];
  $langcode = $element['#language'];
  $parents = $element['#field_parents'];

  $submitted_values = drupal_array_get_nested_value($form_state['values'], array_slice($button['#array_parents'], 0, -2));
  foreach ($submitted_values as $delta => $submitted_value) {
    if (!$submitted_value['fid']) {
      unset($submitted_values[$delta]);
    }
  }

  // Re-index deltas after removing empty items.
  $submitted_values = array_values($submitted_values);

  // Update form_state values.
  drupal_array_set_nested_value($form_state['values'], array_slice($button['#array_parents'], 0, -2), $submitted_values);

  // Update items.
  $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
  $field_state['items'] = $submitted_values;
  field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);

  $form_state['rebuild'] = true;
}

function aia_contact_ajax_add($form, &$form_state) {
  return $form[$form_state['#triggering_element']['#array_parents'][0]];
}

function aia_contacts_field_widget_process($element, &$form_state, $form) {
  $item['value'] = $element['value']['#default_value'];

  $field = field_widget_field($element, $form_state);

//  $element['#theme'] = 'file_widget';

//  if (!empty($item['value'])) {
//    $element['action'] = array(
//      '#type' => 'submit',
//      '#value' => t('Delete'),
//    );
//  }

//  foreach (array('upload_button', 'remove_button') as $key) {
//    $element[$key]['#submit'][] = 'file_field_widget_submit';
//    $element[$key]['#limit_validation_errors'] = array(array_slice($element['#parents'], 0, -1));
//  }

  return $element;
}

/**
 * @param $element
 * @param $form_state
 * @param $form
 * @return array
 */
function aia_contacts_field_widget_process_multiple($element, &$form_state, $form) {
  $element_children = element_children($element, TRUE);
  $count = count($element_children);

  foreach ($element_children as $delta => $key) {
    if ($key != $element['#aia_contact_delta']) {

      $element[$key]['_weight'] = array(
        '#type' => 'weight',
        '#title' => t('Weight for new contact'),
        '#title_display' => 'invisible',
        '#delta' => $count,
        '#default_value' => $delta,
      );
    }
    else {
      // The title needs to be assigned to the upload field so that validation
      // errors include the correct widget label.
      $element[$key]['#title'] = $element['#title'];
      $element[$key]['_weight'] = array(
        '#type' => 'hidden',
        '#default_value' => $delta,
      );
    }
  }

  // Add a new wrapper around all the elements for Ajax replacement.
  $element['#prefix'] = '<div id="' . $element['#id'] . '-ajax-wrapper">';
  $element['#suffix'] = '</div>';

  return $element;
}

/**
 * @param $variables
 * @return string
 */
function theme_aia_contacts_widget_multiple($variables) {
  $element = $variables['element'];

  // Special ID and classes for draggable tables.
  $weight_class = $element['#id'] . '-weight';
  $table_id = $element['#id'] . '-table';

  // Build up a table of applicable fields.
  $headers = array();
  $headers[] = t('Contact type');
  $headers[] = t('Contact value');

//  kpr($element);
//  if ($element['#display_field']) {
//    $headers[] = array(
//      'data' => t('Display'),
//      'class' => array('checkbox'),
//    );
//  }

  $headers[] = t('Weight');
  $headers[] = t('Operations');


  // Get our list of widgets in order (needed when the form comes back after
  // preview or failed validation).
  $widgets = array();
  foreach (element_children($element) as $key) {
    $widgets[] = &$element[$key];
  }

  usort($widgets, '_field_sort_items_value_helper');

  $rows = array();
  foreach ($widgets as $key => &$widget) {
    // Save the uploading row for last.
//    if ($widget['#file'] == FALSE) {
//      $widget['#title'] = $element['#file_upload_title'];
//      $widget['#description'] = $element['#file_upload_description'];
//      continue;
//    }

    // Delay rendering of the buttons, so that they can be rendered later in the
    // "operations" column.
    $operations_elements = array();

    foreach (element_children($widget) as $sub_key) {
      if (isset($widget[$sub_key]['#type']) && $widget[$sub_key]['#type'] == 'submit') {
        hide($widget[$sub_key]);
        $operations_elements[] = &$widget[$sub_key];
      }
    }

    // Delay rendering of the "Display" option and the weight selector, so that
    // each can be rendered later in its own column.
//    if ($element['#display_field']) {
//      hide($widget['display']);
//    }

    hide($widget['_weight']);

    // Render everything else together in a column, without the normal wrappers.
    $widget['#theme_wrappers'] = array();
//    $information = drupal_render($widget);

    // Render the previously hidden elements, using render() instead of
    // drupal_render(), to undo the earlier hide().
    $operations = '';
    foreach ($operations_elements as $operation_element) {
      $operations .= render($operation_element);
    }
    $display = '';
//    if ($element['#display_field']) {
//      unset($widget['display']['#title']);
//      $display = array(
//        'data' => render($widget['display']),
//        'class' => array('checkbox'),
//      );
//    }
    $widget['_weight']['#attributes']['class'] = array($weight_class);
    $weight = render($widget['_weight']);

    // Arrange the row with all of the rendered columns.
    $row = array();
    $row[] = drupal_render($widget['type']);
    $row[] = drupal_render($widget['value']);
//    if ($element['#display_field']) {
//      $row[] = $display;
//    }
    $row[] = $weight;
    $row[] = $operations;
    $rows[] = array(
      'data' => $row,
      'class' => isset($widget['#attributes']['class']) ? array_merge($widget['#attributes']['class'], array('draggable')) : array('draggable'),
    );
  }

  drupal_add_tabledrag($table_id, 'order', 'sibling', $weight_class);

  $output = '';
  $output = empty($rows) ? '' : theme('table', array('header' => $headers, 'rows' => $rows, 'attributes' => array('id' => $table_id)));
  $output .= drupal_render_children($element);
  return $output;
}

function aia_contacts_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
    kpr($entity_type);
  kpr($entity);
  kpr($field);
  kpr($instance);
  kpr($items);
}

//function aia_contacts_field_insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
//  kpr($entity_type);
//  kpr($entity);
//  kpr($field);
//  kpr($instance);
//  kpr($items);
//  if(sizeof($items) > 0) {
//    $entity_id = entity_id($entity_type, $entity);
//
//    $query = db_insert('taxonomy_index')->fields(array('nid', 'tid', 'sticky', 'created', ));
//
//    foreach($items as $delta => $item) {
//      $contact = array(
//        'entity_type' => $entity_type,
//        'bundle' => $instance['bundle'],
//        'entity_id' => $entity_id,
//        'revision_id' => isset($entity->revision) & $entity->revision ? $entity->revision : $entity_id,
//        'language' => isset($entity->language)  ? $entity->language : LANGUAGE_NONE,
//        'delta' => $delta,
//        'field_contacts_type' => $item['type'],
//        'field_contacts_value' => $item['value'],
//      );
//
//
//    }
//  }
//  if (variable_get('taxonomy_maintain_index_table', TRUE) && $field['storage']['type'] == 'field_sql_storage' && $entity_type == 'node' && $entity->status) {
//    $query = db_insert('taxonomy_index')->fields(array('nid', 'tid', 'sticky', 'created', ));
//    foreach ($items as $item) {
//      $query->values(array(
//        'nid' => $entity->nid,
//        'tid' => $item['tid'],
//        'sticky' => $entity->sticky,
//        'created' => $entity->created,
//      ));
//    }
//    $query->execute();
//  }
//}

/**
 * Implements hook_field_widget_error().
 */
function aia_contacts_field_widget_error($element, $error, $form, &$form_state) {
  form_error($element, $error['message']);
}

/**
 * Implements hook_field_settings_form().
 */
//function aia_contacts_field_settings_form($field, $instance, $has_data) {
//// Get proper values for 'allowed_values_function', which is a core setting.
//  $vocabularies = taxonomy_get_vocabularies();
//  $options = array();
//  foreach ($vocabularies as $vocabulary) {
//    $options[$vocabulary->machine_name] = $vocabulary->name;
//  }
//  $form['allowed_values'] = array(
//    '#tree' => TRUE,
//  );
//
//  foreach ($field['settings']['allowed_values'] as $delta => $tree) {
//    $form['allowed_values'][$delta]['vocabulary'] = array(
//      '#type' => 'select',
//      '#title' => t('Vocabulary'),
//      '#default_value' => $tree['vocabulary'],
//      '#options' => $options,
//      '#required' => TRUE,
//      '#description' => t('The vocabulary which supplies the options for this field.'),
//      '#disabled' => $has_data,
//    );
//    $form['allowed_values'][$delta]['parent'] = array(
//      '#type' => 'value',
//      '#value' => $tree['parent'],
//    );
//  }
//
//  return $form;
//}